import dayjs from 'dayjs';

type CompareType = 'year-on-year' | 'month-on-month';

type DateRange = [Date, Date];

/**
 * 获取同比和环比时间
 * @param compareType
 * @param range
 * @param type
 */
export function getDateRange(
  compareType: CompareType,
  range: DateRange,
  type: 'day' | 'week' | 'month' | 'year' | 'quarter',
): [string, string] {
  const [startDate, endDate] = range;

  const addDays = (date: Date, days: number): Date => {
    const result = new Date(date);
    result.setDate(result.getDate() + days);
    return result;
  };

  const addWeeks = (date: Date, weeks: number): Date => {
    return addDays(date, weeks * 7);
  };

  const addMonths = (date: Date, months: number): Date => {
    const result = new Date(date);
    result.setMonth(result.getMonth() + months);
    return result;
  };

  const addYears = (date: Date, years: number): Date => {
    const result = new Date(date);
    result.setFullYear(result.getFullYear() + years);
    return result;
  };

  let newStartDate: Date;
  let newEndDate: Date;

  const daysDiff = Math.ceil(
    (endDate.getTime() - startDate.getTime()) / (1000 * 3600 * 24),
  );

  switch (compareType) {
    case 'year-on-year':
      newStartDate = addYears(startDate, -1);
      newEndDate = addYears(endDate, -1);
      break;

    case 'month-on-month':
      if (type == 'week') {
        newStartDate = addWeeks(startDate, -1);
        newEndDate = addWeeks(endDate, -1);
      } else if (type == 'month') {
        newStartDate = addMonths(startDate, -1);
        newEndDate = addMonths(endDate, -1);
      } else {
        newStartDate = addDays(startDate, -1);
        newEndDate = addDays(endDate, -1);
      }
      break;

    default:
      throw new Error('Invalid compare type');
  }

  return [
    dayjs(newStartDate).format('YYYY-MM-DD'),
    dayjs(newEndDate).format('YYYY-MM-DD'),
  ];
}

export function getTimeRange(now: dayjs.Dayjs, type: 'day' | 'week' | 'month') {
  let startDate: dayjs.Dayjs;
  let endDate = now.add(0, 'day');

  switch (type) {
    case 'day':
      startDate = now.add(0, 'day');
      break;
    case 'week':
      startDate = now.startOf('week');
      endDate = now.endOf('week');
      break;
    case 'month':
      startDate = now.startOf('month');
      endDate = now.endOf('month');
      break;
    default:
      startDate = now.add(-1, 'day');
      break;
  }
  return [
    startDate.format('YYYY-MM-DD 00:00:00'),
    endDate.format('YYYY-MM-DD 23:59:59'),
  ];
}
